<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" top="5vh" @close="cancel" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="指南条目：" prop="guideName">
              <el-input v-model="form.guideName" placeholder="请输入指南条目" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申报单位：" prop="departmentName">
              <el-input v-model="form.departmentName" placeholder="请输入申报单位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目负责人：" prop="projectHeader">
              <el-input v-model="form.projectHeader" placeholder="请输入项目负责人" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="评审结果：" prop="reviewResults">
              <el-select style="width: 100%;" v-model="form.reviewResults" placeholder="请选择评审结果">
                <el-option v-for="item in resultList" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平均分：" prop="avgScore">
              <el-input v-model="form.avgScore" type="number" oninput="if(value<0)value=0" placeholder="请输入平均分" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回避数：" prop="avoidCount">
              <el-input v-model="form.avoidCount" type="number" oninput="if(value<0)value=0" placeholder="请输入回避数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="评审结论：" prop="reviewResultContent">
              <el-input v-model="form.reviewResultContent" type="textarea" rows="7" placeholder="请输入评审结论" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="评审意见：" prop="reviewOpinion">
              <el-input v-model="form.reviewOpinion" type="textarea" rows="7" placeholder="请输入评审意见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="专家组：" prop="name4">
            <el-button type="primary" @click="addUser">添加专家组</el-button>
          </el-form-item>
          <TableCompEle class="m-t" ref="multipleTable" :tableData="tableData" :tableConfig="tableConfigDialog" :tableAction="tableAction"
            rowKey="userId" :isSelect="false" :isIndex="true">
            <template v-slot:upload="scope">
              <span>
                <el-upload ref="uploadRef" class="upload-demo" action="#" :limit="1"
                  :on-change="(file, fileList) => {handleChange(file, fileList, scope.row)}" :auto-upload="false" :show-file-list="false"
                  :on-exceed="handleExceed">
                  <template #trigger>
                    <el-link :underline="false" type="primary">上传</el-link>
                  </template>
                </el-upload>
              </span>
            </template>
          </TableCompEle>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="添加评审专家" :visible.sync="drawer" direction="rtl" size="50%" :close-on-press-escape="false" :wrapperClosable="false"
      :before-close="handleClose">
      <div class="p-l p-r">
        <div class="">
          <SearchComp :searchForm="searchForm" :searchData="queryString" :searchAction="searchAction"></SearchComp>
        </div>
        <div class="">
          <TableCompEle class="m-t" ref="multipleAllTableUser" :tableData="allTableData" :tableConfig="tableConfig" rowKey="talentsId"
            :isSelect="true" :isIndex="true" @handleSelectionChange="handleSelectionChange"></TableCompEle>
        </div>
      </div>
    </el-drawer>
    <PreviewPdf v-if="showPdf" :pdfUrl="pdfUrl" @closeLookPdf="closeLookPdf" />
  </div>
</template>

<script>
// import {
//   uploadFile,
//   getExpertList,
//   getSelect,
//   getWord2Pdf
// } from '@/api/common.js'
import { addReviewResult, getResultDetail } from '@/api/projectDeclare.js'

import PreviewPdf from '@/views/common/previewPdf.vue'
export default {
  components: { PreviewPdf },
  data() {
    return {
      showPdf: false,
      pdfUrl: null,
      drawer: false,
      dialogVisible: false,
      accept: '.doc,.docx,.pdf',
      title: '',
      form: {
        guideName: '',
        departmentName: '',
        projectHeader: '',
        reviewOpinion: '',
        reviewResults: '',
        reviewResultContent: ''
      },
      rules: {
        guideName: [
          { required: true, message: '指南条目不能为空！', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '申报单位不能为空！', trigger: 'blur' }
        ],
        projectHeader: [
          { required: true, message: '项目负责人不能为空！', trigger: 'blur' }
        ],
        reviewResultContent: [
          { required: true, message: '评审结论不能为空！', trigger: 'blur' }
        ],
        reviewOpinion: [
          { required: true, message: '评审意见不能为空！', trigger: 'blur' }
        ],
        reviewResults: [
          { required: true, message: '评审结果不能为空！', trigger: 'chang' }
        ]
      },
      selectData: [],
      resultList: [],
      tableData: [],
      allTableData: [],
      tableConfig: [
        {
          prop: 'talentsName',
          label: '专家姓名'
        },
        {
          prop: 'jobTitle',
          label: '技术职称'
        },
        {
          prop: 'careerDirection',
          label: '职业方向'
        },
        {
          prop: 'labelStr',
          label: '标签'
        }
      ],
      tableConfigDialog: [
        {
          prop: 'talentsName',
          label: '专家姓名',
          width: 150
        },
        {
          isEdit: true,
          isType: 'Select',
          prop: 'groupTitle',
          label: '职责',
          placeholder: '请选择',
          width: 120,
          options: [
            {
              label: '组长',
              value: '组长'
            },
            {
              label: '组员',
              value: '组员'
            }
          ]
        },
        {
          prop: 'jobTitle',
          label: '技术职称',
          width: 120
        },
        {
          prop: 'careerDirection',
          label: '职业方向',
          width: 140
        },
        {
          isEdit: true,
          isType: 'Textarea',
          prop: 'reviewOpinion',
          label: '专家意见',
          placeholder: '请输入'
        },
        {
          isLink: true,
          prop: 'fileName',
          type: 'primary',
          label: '文件',
          width: 150,
          method: row => {
            this.downloadLink(row)
          }
        }
      ],
      tableAction: {
        align: () => 'center',
        width: () => String(220),
        operations: [
          {
            label: '预览',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.filePath
            },
            method: row => {
              this.lookLink(row)
            }
          },
          {
            label: '下载',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.filePath
            },
            method: row => {
              this.downloadLink(row)
            }
          },
          {
            prop: 'upload',
            isSlot: true
          },
          {
            label: '修改',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return !row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', true)
            }
          },
          {
            label: '保存',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', false)
            }
          },
          {
            label: '删除',
            isLink: true,
            type: 'danger',
            method: row => {
              let itemIndex = this.tableData.findIndex(function (obj) {
                return row === obj
              })
              this.tableData.splice(itemIndex, 1)
            }
          }
        ]
      },
      queryString: {
        talentsName: '',
        jobTitle: ''
      },
      searchForm: {
        changeMethod: () => this.getUsers(),
        formData: [
          {
            type: 'Input',
            label: '专家姓名',
            prop: 'talentsName',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入专家姓名'
          },
          {
            type: 'Input',
            label: '技术职称',
            prop: 'jobTitle',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入技术职称'
          }
        ]
      },
      searchAction: [
        {
          label: '查询',
          type: 'primary',
          handle: () => {
            this.getUsers()
          }
        },
        {
          label: '重置',
          type: 'primary',
          plain: true,
          handle: () => {
            this.queryString = {
              talentsName: '',
              jobTitle: ''
            }
            this.getUsers()
          }
        }
      ]
    }
  },
  created() { },
  methods: {
    show(obj) {
      this.dialogVisible = true
      this.title = obj.title
      if (obj.data) {
        this.form = Object.assign(JSON.parse(JSON.stringify(obj.data)))
        // getResultDetail({ projectId: obj.data.id }).then(res => {
        //   if (res.code == 200 && res.data) {
        //     this.form = Object.assign(
        //       JSON.parse(JSON.stringify(obj.data)),
        //       res.data
        //     )
        //     this.form.researchProjectId = obj.data.id
        //     this.tableData = res?.data?.techTalentsList ?? []
        //   }
        // })
      }

      this.getUsers()
    },
    getUsers() {
      getExpertList({
        currentPage: 1,
        pageSize: 100000,
        talentsType: '专家',
        ...this.queryString
      }).then(res => {
        if (res.data && res.data.list) {
          this.allTableData = res.data.list
        } else {
          this.allTableData = []
        }
      })
      // getSelect({ table: '科研指南管理', type: '评审结果' }).then(res => {
      //   this.resultList = res?.data ?? []
      // })
    },
    submitForm() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          // const ids = []
          // this.tableData.forEach(items => {
          //   ids.push(items.talentsId)
          // })
          // this.form.expertGroup = ids.join(',')
          // this.form.researchProjectId = this.form.id
          delete this.form.id
          delete this.form.createTime
          delete this.form.modifyTime
          this.form.techTalentsList = this.tableData
          // addReviewResult(this.form).then(() => {
          //   this.cancel()
          // })
        } else {
          return false
        }
      })
    },
    cancel() {
      this.form = {
        guideName: '',
        departmentName: '',
        projectHeader: '',
        reviewOpinion: '',
        reviewResults: '',
        reviewResultContent: ''
      }
      this.$refs.ruleForm.clearValidate()
      this.tableData = []
      this.dialogVisible = false
      this.$emit('close')
    },
    addUser() {
      this.drawer = true
      this.$nextTick(() => {
        console.log('[ this.tableData ] >', this.tableData)
        this.$refs.multipleAllTableUser.toggleSelection(this.tableData)
      })
    },
    handleClose() {
      this.drawer = false
      // this.tableData = [...this.selectData]
      this.selectData.forEach(item => {
        const existingItem = this.tableData.find(
          bItem => bItem.talentsId === item.talentsId
        )
        if (!existingItem) {
          this.tableData.push(item)
        }
      })
    },
    handleSelectionChange(val) {
      this.selectData = val
    },
    handleChange(file, fileList, row) {
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      // uploadFile(formData).then(res => {
      //   row.fileName = res.data.fileName
      //   row.fileOriginPath = res.data.filePath
      //   row.filePath = res.data.servicePath
      // })
      this.$set(row, 'fileName', row.fileName)
      this.$refs.uploadRef.clearFiles()
    },
    // 多次上传覆盖
    handleExceed(file, row) {
      this.handleChange(file[0], '', row)
    },
    downloadLink(item) {
      this.downloadByUrl(item.fileName, item.filePath)
    },
    lookLink(item) {
      let txt = this.getMatchType(item.filePath)
      if (txt === 'word') {
        getWord2Pdf({ wordPath: item.filePath }).then(res => {
          if (res.data) {
            this.lookPdf(res.data)
          } else {
            this.$message.warning('暂无法预览，请下载后查看！')
          }
        })
      } else {
        if (txt === 'pdf') {
          this.lookPdf(item.filePath)
        } else {
          this.$message.warning('文件不支持预览！')
        }
      }
    },
    lookPdf(url) {
      this.pdfUrl = url
      this.showPdf = true
    },
    closeLookPdf() {
      this.showPdf = false
      this.pdfUrl = null
    }
  }
}
</script>

<style lang="less" scoped>
  .upload-demo {
    display: inline-block;
    padding-right: 10px;
  }
</style>